#include "../base/mq.h"
#include "../base/th.h"

#include <string.h>
#include <stdio.h>
#include <assert.h>
/*
 * Testing the message queue by multi-thread
 */


struct SharedData {
	const char* cmd;
	struct msgqueue* taskqueue;
};


static void* TestProducer( void* argument ) {
	struct SharedData* sd = (struct SharedData*)(argument);
	int msgnum= 0;
	struct th_join_sec s;
	s.sec=0;
	s.micro_sec=1000;
	while(true) {
		if( strcmp(sd->cmd,"EXIT") ==0 ) {
			break;
		}
		++msgnum;
		msgqueue_enqueue(sd->taskqueue,&msgnum);
		/*
		 * Sleep this thread 
		 */
		thread_sleep(&s);
	}

	return NULL;
}


static void* TestConsumer( void* argument ) {
	struct SharedData* sd = (struct SharedData*)(argument);
	void* t;
	struct th_join_sec s;
	s.sec=0;
	s.micro_sec= 1000;
	while(true) {
		t=msgqueue_head(sd->taskqueue);
		if( t!=NULL ) {
			printf("current task number: %d\n",*((int*)(t)));
			if( *((int*)(t)) == 1000 ) {
				sd->cmd="EXIT";
				msgqueue_dequeue(sd->taskqueue);
				return NULL;
			}
			msgqueue_dequeue(sd->taskqueue);
		}
		thread_sleep(&s);
	}
	return NULL;
}


void test() {
	struct SharedData sd;
	thread_handler th1,th2;
	sd.taskqueue = msgqueue_create(10,sizeof(int));
	sd.cmd = "";
	assert(
		thread_create(&th1,"th1",TestProducer,&sd,false) &&
		thread_create(&th2,"th2",TestConsumer,&sd,false) );
	thread_join(th1,NULL,NULL);
	thread_join(th2,NULL,NULL);
}